package com.wing.user.service;

import chat.qiye.wechat.sdk.api.contact.resp.ContactDeptListResp;
import chat.qiye.wechat.sdk.api.contact.vo.ContactDeptVo;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.user.dao.DepartmentDao;
import com.wing.user.model.entity.CompanyInfo;
import com.wing.user.model.entity.Department;
import com.wing.user.model.entity.User;
import com.wing.user.model.request.DepartmentForm;
import com.wing.user.model.response.DepartmentVO;
import com.wing.user.model.response.NodeDataVO;
import com.wing.user.model.response.UserAuthVO;
import com.wing.user.model.response.UserVO;
import com.wing.web.excel.DepartmentExcelIn;
import com.wing.web.excel.UseInventoryUserExcelIn;
import com.wing.web.utils.JwtUtils;
import com.wing.wecom.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 部门架构-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class DepartmentServiceImpl extends ServiceImpl<DepartmentDao, Department> implements DepartmentService {

    @Autowired
    private DeptService deptService;
    @Autowired
    private CompanyInfoService companyInfoService;

    @Override
    @Transactional(readOnly=false)
    public int add(DepartmentForm departmentForm) {

        //校验

        Department department =new Department();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(Department.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(departmentForm, department, copyOptions);

        // 企业微信对接
        // 获取部门表中企业微信ID最大值
        /*Integer maxQywxDeptId = baseMapper.getMaxQywxDeptId();
        // 获取企业微信部门ID最大值
        ContactDeptListResp contactDeptListResp = deptService.list(null);
        if(contactDeptListResp.getDepartment().size() > 0){
            Integer id = contactDeptListResp.getDepartment().get(contactDeptListResp.getDepartment().size()-1).getId();
            if(null == maxQywxDeptId || id > maxQywxDeptId){
                maxQywxDeptId = id;
            }
        }
        if(maxQywxDeptId != null){
            department.setQywxDeptId(maxQywxDeptId+1);
        }else{
            department.setQywxDeptId(2);
        }*/
        if(null == department.getParentId()){
            department.setParentId(-1l);
        }
        int i = baseMapper.insert(department);
        if(i > 0){
            // 添加企业微信部门
            /*ContactDeptVo contactDeptVo = new ContactDeptVo();
            contactDeptVo.setName(department.getName()); // 部门名称
            contactDeptVo.setNameEn(null); // 英文名称
            Department dept = baseMapper.selectById(department.getParentId()); // 获取父级部门
            if(dept != null && dept.getQywxDeptId() != null){
                contactDeptVo.setParentid(dept.getQywxDeptId()); // 父部门id
            }else{
                contactDeptVo.setParentid(1); // 父部门id
            }
            contactDeptVo.setOrder(null); // 在父部门中的次序值。order值大的排序靠前。有效的值范围是[0, 2^32)
            contactDeptVo.setId(department.getQywxDeptId()); // 企业微信部门ID
            i = deptService.create(contactDeptVo);
            if(i == 0){
                throw new BusinessException(300, "创建企业微信部门失败");
            }*/
        }
        return i;
    }

    @Override
    @Transactional(readOnly=false)
    public boolean update(Department department) {
        int i = baseMapper.updateById(department);

        // 企业微信对接
        if(i > 0){
            // 更新企业微信部门
            /*ContactDeptVo contactDeptVo = new ContactDeptVo();
            contactDeptVo.setName(department.getName()); // 部门名称
            contactDeptVo.setNameEn(null); // 英文名称
            Department dept = baseMapper.selectById(department.getParentId()); // 获取父级部门
            if(dept != null && dept.getQywxDeptId() != null){
                contactDeptVo.setParentid(dept.getQywxDeptId()); // 父部门id
            }else{
                contactDeptVo.setParentid(1); // 父部门id
            }
            contactDeptVo.setOrder(null); // 在父部门中的次序值。order值大的排序靠前。有效的值范围是[0, 2^32)
            contactDeptVo.setId(department.getQywxDeptId()); // 企业微信部门ID
            i = deptService.update(contactDeptVo);
            if(i == 0){
                throw new BusinessException(300, "更新企业微信部门失败");
            }*/
        }
        return i > 0;
    }

    @Override
    public List<DepartmentVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<DepartmentVO> pageList4app(Page page, Map<String, Object> params) {
        List<DepartmentVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public DepartmentVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    @Transactional(readOnly=false)
    public boolean delete(Long departmentId) {
        Department department = baseMapper.selectById(departmentId); // 获取当前删除的部门信息
        Integer qywxDeptId = department.getQywxDeptId(); // 获取企业微信部门ID
        // 查询是否存在子部门
        int count = baseMapper.selectCount(new QueryWrapper<Department>().eq("parent_id", department.getId()));
        if(count > 0){
            throw new BusinessException(500, "请先删除子部门");
        }
        int i = baseMapper.deleteById(department);
        // 企业微信对接
        if(i > 0){
            // 删除企业微信部门
            /*i = deptService.delete(qywxDeptId);
            if(i == 0){
                throw new BusinessException(300, "删除企业微信部门失败");
            }*/
        }
        return i > 0;
    }

    @Override
    public void importExcel(List<DepartmentExcelIn> list) {
        try {
            addExcel(list);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<DepartmentExcelIn> exportList(Map paramsMap) {
        return baseMapper.exportList(paramsMap);
    }

    @Transactional(readOnly = false)
    void addExcel(List<DepartmentExcelIn> list){
        int i = 1;
        for (DepartmentExcelIn item : list) {
            i++;
            if(StringUtils.isBlank(item.getCompanyInfoName())){
                throw new BusinessException(300, "第"+i+"行企业未输入数据");
            }
            if(StringUtils.isBlank(item.getName())){
                throw new BusinessException(300, "第"+i+"行名称未输入数据");
            }
            if(StringUtils.isBlank(item.getCode())){
                throw new BusinessException(300, "第"+i+"行编码未输入数据");
            }
            if(StringUtils.isBlank(item.getCostCenter())){
                throw new BusinessException(300, "第"+i+"行成本中心未输入数据");
            }
            Department department = new Department();
            // 获取企业
            CompanyInfo companyInfo = companyInfoService.getOne(new QueryWrapper<CompanyInfo>().eq("name", item.getCompanyInfoName()));
            if(companyInfo == null){
                throw new BusinessException(300, "该企业数据不存在");
            }
            department.setCompanyInfoId(companyInfo.getId());
            department.setName(item.getName());
            department.setCode(item.getCode());
            department.setCostCenter(item.getCostCenter());
            department.setParentId(-1L);
            // 获取上级部门
            Department parentDepartment = baseMapper.selectOne(new QueryWrapper<Department>().eq("name", item.getParentName()));
            if(StringUtils.isNotBlank(item.getParentName())){
                if(parentDepartment != null){
                    department.setParentId(parentDepartment.getId());
                }else{
                    throw new BusinessException(300, "该上级部门数据不存在");
                }
            }


            QueryWrapper<Department> companyInfoWrapper = new QueryWrapper<>();
            companyInfoWrapper.eq("name", item.getName());
            companyInfoWrapper.eq("company_info_id", companyInfo.getId());
            Department companyInfoOne = baseMapper.selectOne(companyInfoWrapper);
            if(companyInfoOne != null){
                throw new BusinessException(300, "第"+i+"行名称已存在数据库！");
            }
            QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("code", item.getCode());
            Department one = baseMapper.selectOne(queryWrapper);
            if(one != null){
                throw new BusinessException(300, "第"+i+"行编码已存在数据库！");
            }
            QueryWrapper<Department> wrapper = new QueryWrapper<>();
            wrapper.eq("cost_center", item.getCostCenter());
            Department oneCostCenter = baseMapper.selectOne(wrapper);
            if(oneCostCenter != null){
                throw new BusinessException(300, "第"+i+"行成本中心已存在数据库！");
            }
            // 获取人员
            User user = baseMapper.getByUsername(item.getPrincipal());
            if(user == null){
                throw new BusinessException(300, "该负责人数据不存在");
            }
            department.setPrincipal(user.getId());
            Boolean isFinalVal = false;
            if(StringUtils.isNotBlank(item.getIsFinalVal()) && item.getIsFinalVal().indexOf("是") != -1){
                isFinalVal = true;
            }
            department.setIsFinal(isFinalVal);
            department.setIsDeleted(true);
            if(baseMapper.insert(department)<= 0){
                throw new BusinessException(500, "导入失败");
            }
        }
    }

    public JsonResult getTreeData(Long companyId){
        Map paramMap=new HashMap();
        paramMap.put("companyInfoId",companyId);
        List<DepartmentVO> list=baseMapper.list4app(paramMap);
        Map<Long,List<NodeDataVO>> map=new HashMap<>();
        for (DepartmentVO category:list) {
            if (map.containsKey(category.getParentId())){
                NodeDataVO nodeDataVO=new NodeDataVO();
                nodeDataVO.setValue(category.getId().toString());
                nodeDataVO.setName(category.getName());
                map.get(category.getParentId()).add(nodeDataVO);
            }else{
                List<NodeDataVO> tmpList=new ArrayList<>();
                NodeDataVO nodeDataVO=new NodeDataVO();
                nodeDataVO.setValue(category.getId().toString());
                nodeDataVO.setName(category.getName());
                tmpList.add(nodeDataVO);
                map.put(category.getParentId(),tmpList);
            }
        }
        List<NodeDataVO> rootList=map.get(-1L);
        if (rootList==null){
            return JsonResult.success();
        }
        constructTree(rootList,map);
        return JsonResult.success(rootList);
    }

    private void  constructTree(List<NodeDataVO> parentList,Map<Long,List<NodeDataVO>> dataMap){
        for (NodeDataVO node:parentList) {
            Long nodeId=Long.valueOf(node.getValue());
            List<NodeDataVO> childList=dataMap.get(nodeId);
            if (childList!=null){
                node.setChildren(childList);
                constructTree(childList,dataMap);
            }
        }
    }

    @Override
    public List<DepartmentVO> getDeptTree() {
        return baseMapper.listDeptTree();
    }

}
